<?php
declare(strict_types=1);
namespace Cache\Driver;
use Cache\CacheInterface;
use Config;
use Memcache;

class MemcacheStorage implements CacheInterface
{
    /**
     * 缓存前缀
     * @var string|null
     */
    private ?string $prefix = null;

    protected ?Memcache $object = null;

    /**
     * 初始化
     * @param string|null $prefix
     */
    public function __construct(?string $prefix = null)
    {
        if (!extension_loaded("memcache")) exit("memcache扩展未安装！");
        $config = Config::get("memcached");
        $this->prefix = $prefix;
        $this->object = new Memcache();
        $this->object->connect($config['host'],(int)$config['port']);
    }

    /**
     * 自加
     * @param string $name
     * @param int $step
     * @return bool|int
     */
    public function inc(string $name, int $step = 1): bool|int
    {
        return $this->object->increment($name,$step);
    }

    /**
     * 自减
     * @param string $name
     * @param int $step
     * @return bool|int
     */
    public function dec(string $name, int $step = 1): bool|int
    {
        return $this->object->decrement($name,$step);
    }

    /**
     * @inheritDoc
     */
    public function get(array|string $name): mixed
    {
        // TODO: Implement get() method.
        return $this->object->get($this->prefix.$name);
    }

    /**
     * @inheritDoc
     */
    public function set(string $name, mixed $value, ?int $expire = null): bool
    {
        // TODO: Implement set() method.
        return $this->object->set($this->prefix.$name, $value, $expire?:0);
    }

    /**
     * @inheritDoc
     */
    public function delete(string $name): bool
    {
        // TODO: Implement delete() method.
        return $this->object->delete($this->prefix.$name);
    }

    /**
     * @inheritDoc
     */
    public function flush(): bool
    {
        // TODO: Implement flush() method.
        return $this->object->flush();
    }
}
